package com.lagou.rpc.consumer.proxy;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.consumer.zookeeper.ZookeeperClient;
import lombok.extern.log4j.Log4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
@Log4j
public class RpcClientProxy {
    private static String connectString = "192.168.200.20:2181";
    private static int sessionTimeout = 60000;

    static String path = "/lg-rpc-provider";
    static volatile int version = 10;

    static RpcClient getRpcClient() {
        RpcClient rpcClient1 = new RpcClient("127.0.0.1", 8899);
        RpcClient rpcClient2 = new RpcClient("127.0.0.1", 9999);
        List<RpcClient> list = new ArrayList();
        if (rpcClient1.getChannel() != null) {
            list.add(rpcClient1);
        }
        if (rpcClient2.getChannel() != null) {
            list.add(rpcClient2);
        }
        Random random = new Random();
        int i = random.nextInt(list.size());
        RpcClient rpcClient = list.get(i);
        return rpcClient;
    }


    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //开始执行时间
                        long start = System.currentTimeMillis();
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
//                        RpcClient rpcClient = new RpcClient("127.0.0.1", 8899);
                        //每次都选择最后一次响应时间短的服务端进行服务调用
                        //todo
                        ZookeeperClient zookeeperClient = new ZookeeperClient();
                        zookeeperClient.getConnect();
                        String service = zookeeperClient.getFastServer(zookeeperClient);
                        String[] split = service.split(":");
                        log.info("本次调用的服务是：" + service);
                        String ip = split[0];
                        int port = Integer.parseInt(split[1]);
                        RpcClient rpcClient = new RpcClient(ip, port);
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                            long end = System.currentTimeMillis();
                            long cost = end - start;
                            String now = DateUtil.now();
                            System.out.println("本次花费时间：" + cost + "ms" + ";本此结束时间为：" + now + ";响应的服务器是：" + service);
                            zookeeperClient.getZk().setData("/lg-rpc-provider/" + service, String.valueOf(cost).getBytes(), -1);
                        }
                    }
                });
    }
}
